# import shutil
#
# import requests
# import os
#
# root = 'static/百度乐玩'
# if os.path.exists(root):
#     shutil.rmtree(root)
#
# os.mkdir(root)
#
# url = 'https://lewan.baidu.com/lewanapi?action=aladdin_rank_games&gameSource=standalone'
#
# res = requests.get(url)
#
# items = res.json()['result']['data']['annual']
# print(len(items))
#
# for item in items:
#     name_id = item['gameId']
#     name = item['gameName']
#     img_url = item['gameIcon']
#     detail_url = item['gameSpecialUrl']
#
#     # print(name_id ,name, img_url, detail_url)
#     img_res = requests.get(img_url).content
#
#     with open(f'{root}/{name}.png', "wb") as f:
#         f.write(img_res)
#
#     score_url = f'https://lewan.baidu.com/lewanapi?action=game_comments&gameId={name_id}'
#     score_res = requests.get(score_url)
#     score = score_res.json()['result']['data']['score']
#     print(f'{name}的评分是{score}')

# import shutil
# import os
# import asyncio
# import aiohttp
# import aiofiles
#
#
# async def download_image(session, url, filepath):
#     """异步下载图片"""
#     try:
#         async with session.get(url) as response:
#             if response.status == 200:
#                 # 异步写入文件
#                 async with aiofiles.open(filepath, 'wb') as f:
#                     await f.write(await response.read())
#                 return True
#             else:
#                 print(f"下载图片失败: {url}, 状态码: {response.status}")
#                 return False
#     except Exception as e:
#         print(f"下载图片错误 {url}: {e}")
#         return False
#
#
# async def fetch_score(session, game_id, game_name):
#     """异步获取游戏评分"""
#     try:
#         score_url = f'https://lewan.baidu.com/lewanapi?action=game_comments&gameId={game_id}'
#         async with session.get(score_url) as response:
#             if response.status == 200:
#                 data = await response.json()
#                 score = data['result']['data']['score']
#                 print(f'{game_name}的评分是{score}')
#                 return score
#             else:
#                 print(f"获取评分失败: {game_name}, 状态码: {response.status}")
#                 return None
#     except Exception as e:
#         print(f"获取评分错误 {game_name}: {e}")
#         return None
#
#
# async def process_game(session, item, root):
#     """处理单个游戏：下载图片并获取评分"""
#     name_id = item['gameId']
#     name = item['gameName']
#     img_url = item['gameIcon']
#
#     # 清理文件名中的非法字符
#     safe_name = "".join(c for c in name if c.isalnum() or c in (' ', '-', '_')).rstrip()
#     filepath = f'{root}/{safe_name}.png'
#
#     # 同时下载图片和获取评分
#     download_task = download_image(session, img_url, filepath)
#     score_task = fetch_score(session, name_id, name)
#
#     # 并行执行两个任务
#     results = await asyncio.gather(download_task, score_task, return_exceptions=True)
#
#     return name, results[0], results[1]  # 返回名称、下载结果、评分
#
#
# async def main():
#     """主协程函数"""
#     # 创建目录
#     root = 'static/百度乐玩'
#     if os.path.exists(root):
#         shutil.rmtree(root)
#     os.makedirs(root, exist_ok=True)
#
#     # 获取游戏列表
#     url = 'https://lewan.baidu.com/lewanapi?action=aladdin_rank_games&gameSource=standalone'
#
#     # 使用异步会话
#     async with aiohttp.ClientSession() as session:
#         try:
#             async with session.get(url) as response:
#                 if response.status == 200:
#                     data = await response.json()
#                     items = data['result']['data']['annual']
#                     print(f"找到 {len(items)} 个游戏")
#
#                     # 创建所有游戏的处理任务
#                     tasks = []
#                     for item in items:
#                         task = process_game(session, item, root)
#                         tasks.append(task)
#
#                     # 限制并发数量，避免请求过于频繁
#                     semaphore = asyncio.Semaphore(10)  # 同时最多10个并发请求
#
#                     async def bounded_process_game(session, item, root):
#                         async with semaphore:
#                             return await process_game(session, item, root)
#
#                     # 重新创建带限制的任务
#                     limited_tasks = [
#                         bounded_process_game(session, item, root)
#                         for item in items
#                     ]
#
#                     # 等待所有任务完成
#                     results = await asyncio.gather(*limited_tasks, return_exceptions=True)
#
#                     # 统计结果
#                     success_count = 0
#                     for result in results:
#                         if isinstance(result, Exception):
#                             print(f"任务执行出错: {result}")
#                         else:
#                             name, download_success, score = result
#                             if download_success:
#                                 success_count += 1
#
#                     print(f"\n下载完成! 成功下载 {success_count}/{len(items)} 个游戏图标")
#
#                 else:
#                     print(f"获取游戏列表失败，状态码: {response.status}")
#
#         except Exception as e:
#             print(f"主程序错误: {e}")
#
#
# def run_async():
#     """运行异步版本的入口函数"""
#     # 在Windows上需要使用特定的事件循环策略
#     if os.name == 'nt':
#         asyncio.set_event_loop_policy(asyncio.WindowsProactorEventLoopPolicy())
#
#     # 运行主协程
#     asyncio.run(main())
#
#
# # 进度显示版本（可选）
# async def main_with_progress():
#     """带进度显示的主协程"""
#     root = 'static/百度乐玩'
#     if os.path.exists(root):
#         shutil.rmtree(root)
#     os.makedirs(root, exist_ok=True)
#
#     url = 'https://lewan.baidu.com/lewanapi?action=aladdin_rank_games&gameSource=standalone'
#
#     async with aiohttp.ClientSession() as session:
#         try:
#             async with session.get(url) as response:
#                 if response.status == 200:
#                     data = await response.json()
#                     items = data['result']['data']['annual']
#                     total = len(items)
#                     print(f"找到 {total} 个游戏")
#
#                     # 使用信号量限制并发
#                     semaphore = asyncio.Semaphore(5)  # 更保守的并发数
#
#                     async def process_with_progress(session, item, root, index, total):
#                         async with semaphore:
#                             name_id = item['gameId']
#                             name = item['gameName']
#                             img_url = item['gameIcon']
#
#                             safe_name = "".join(c for c in name if c.isalnum() or c in (' ', '-', '_')).rstrip()
#                             filepath = f'{root}/{safe_name}.png'
#
#                             # 显示进度
#                             print(f"[{index + 1}/{total}] 处理: {name}")
#
#                             # 并行下载和获取评分
#                             download_task = download_image(session, img_url, filepath)
#                             score_task = fetch_score(session, name_id, name)
#
#                             download_success, score = await asyncio.gather(
#                                 download_task, score_task, return_exceptions=True
#                             )
#
#                             # 处理可能的异常
#                             if isinstance(download_success, Exception):
#                                 download_success = False
#                             if isinstance(score, Exception):
#                                 score = None
#
#                             return download_success
#
#                     # 创建所有任务
#                     tasks = [
#                         process_with_progress(session, item, root, i, total)
#                         for i, item in enumerate(items)
#                     ]
#
#                     # 执行所有任务
#                     results = await asyncio.gather(*tasks, return_exceptions=True)
#
#                     # 统计成功数量
#                     success_count = sum(1 for r in results if r is True)
#                     print(f"\n完成! 成功下载 {success_count}/{total} 个游戏图标")
#
#                 else:
#                     print(f"获取游戏列表失败: {response.status}")
#
#         except Exception as e:
#             print(f"错误: {e}")
#
#
# # 批量处理版本（处理大量数据）
# async def process_in_batches():
#     """分批处理大量数据"""
#     root = 'static/百度乐玩'
#     if os.path.exists(root):
#         shutil.rmtree(root)
#     os.makedirs(root, exist_ok=True)
#
#     url = 'https://lewan.baidu.com/lewanapi?action=aladdin_rank_games&gameSource=standalone'
#
#     async with aiohttp.ClientSession() as session:
#         try:
#             async with session.get(url) as response:
#                 if response.status == 200:
#                     data = await response.json()
#                     items = data['result']['data']['annual']
#                     total = len(items)
#
#                     batch_size = 20  # 每批处理20个
#                     success_count = 0
#
#                     for batch_start in range(0, total, batch_size):
#                         batch_end = min(batch_start + batch_size, total)
#                         batch_items = items[batch_start:batch_end]
#
#                         print(f"处理批次 {batch_start // batch_size + 1}: {batch_start}-{batch_end - 1}")
#
#                         # 处理当前批次
#                         tasks = []
#                         for item in batch_items:
#                             task = process_game(session, item, root)
#                             tasks.append(task)
#
#                         batch_results = await asyncio.gather(*tasks, return_exceptions=True)
#
#                         # 统计当前批次成功数
#                         batch_success = sum(1 for r in batch_results if not isinstance(r, Exception) and r[1])
#                         success_count += batch_success
#
#                         print(f"批次完成: {batch_success}/{len(batch_items)} 成功")
#
#                         # 批次间延迟，避免请求过于频繁
#                         await asyncio.sleep(1)
#
#                     print(f"\n所有批次完成! 总计成功: {success_count}/{total}")
#
#                 else:
#                     print(f"获取数据失败: {response.status}")
#
#         except Exception as e:
#             print(f"批量处理错误: {e}")
#
#
# if __name__ == "__main__":
#     print("开始异步下载...")
#
#     # 选择要运行的版本：
#
#     # 1. 基础版本
#     # asyncio.run(main())
#
#     # 2. 带进度显示的版本
#     asyncio.run(main_with_progress())

    # 3. 分批处理版本（适合大量数据）
    # asyncio.run(process_in_batches())